package com.glodon.paas.consumer.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.oauth2.client.OAuth2RestOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

import java.net.URI;
import java.util.List;
import java.util.Map;

/**
 * @author Don Li
 */
@Controller
public class OAuth2Endpoint {
    @Autowired
    private OAuth2RestOperations webAgentTemplate;

    @Autowired
    private OAuth2RestOperations deviceTemplate;

    @Autowired
    private OAuth2RestOperations credentialTemplate;
    
    @Autowired
    private OAuth2RestOperations qtoDeviceTemplate;

    @RequestMapping("/oauth2")
    public String devicePage() {
        return "oauth2";
    }

    @RequestMapping("/oauth2/reset")
    @ResponseStatus(HttpStatus.OK)
    public void resetTokens(){
        webAgentTemplate.getOAuth2ClientContext().setAccessToken(null);
        deviceTemplate.getOAuth2ClientContext().setAccessToken(null);
        credentialTemplate.getOAuth2ClientContext().setAccessToken(null);
        qtoDeviceTemplate.getOAuth2ClientContext().setAccessToken(null);
    }

    @RequestMapping("/oauth2/quota")
    public ModelAndView testWebAgent() {
        long quota = webAgentTemplate.getForObject(URI.create("http://localhost:8080/document/api/v2/quota"), Long.class);
        return new ModelAndView(new MappingJacksonJsonView(), "quota", quota);
    }

    @RequestMapping("/oauth2/quota/device")
    public ModelAndView testDevice() {
        long quota = deviceTemplate.getForObject(URI.create("http://localhost:8080/document/api/v2/quota"), Long.class);
        return new ModelAndView(new MappingJacksonJsonView(), "quota", quota);
    }

    @RequestMapping("/oauth2/quota/credential")
    public ModelAndView testCredential() {
        long quota = credentialTemplate.getForObject(URI.create("http://localhost:8080/document/api/v2/quota"), Long.class);
        return new ModelAndView(new MappingJacksonJsonView(), "quota", quota);
    }
    
    @RequestMapping("/oauth2/qto/qtodevice")
    public ModelAndView testQtoDevice() {
    	List<Map> qto = qtoDeviceTemplate.getForObject(URI.create("http://localhost:8080/qto/api/v2/job/list?from=20121211010101&to=20121214010101"),
    			List.class);
        return new ModelAndView(new MappingJacksonJsonView(), "qto", qto);
    }
}
